FenwickTree and Counting Inversions
Not very clever to forget all these.
FenwickTree 树状数组
Common data structure in programming contest to answer range query questions. Simple implementation and less functionalities, $O(n)$extra space, query and edit in $O(logn)$.
Idea: represent every index in binary and save sum of all “smaller” index values, where “smaller” is defined by position of last non-zero bit (001 < 010 < 100, 011< 100).
That is, tree[(100)]=a[(001)]+a[(010)]+a[(011)]+a[(100)]
. And we have tree[(010)]=a[(001)]+a[(010)],tree[(011)]=a[(011)]
, so that we can represent “larger” index with “smaller” one: tree[(100)]=tree[(010)]+tree[(011)]+a[(100)]
by finding the next “smaller” index (caculate by i & (-i)
).
NOTE: to avoid endless loop, we leave tree[0]
zero and start the structure from tree[1]
.
1 | void update(int pos, int v){ |
Counting Inversions Online
Update fenwick tree with update(a[i],1)
when the current number is a[i]. This means we mark a[i] as already presented and we can later count matching inversions use query(a[i],n)
(every number larger than a[i] forms an inversion, so we use fenwick tree to count sum).
Exercise: AtCoder ABC 190 F
每次移动,变化的inverison数量都是规律的,只需要算一次
1 |
|
FenwickTree and Counting Inversions
https://nyte-bk201.github.io/2021/02/23/FenwickTree and Counting Inversions/